package com.jeesite.modules.task.deploy.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.annotation.RepeatSubmit;
import com.jeesite.modules.common.service.SysMsgService;
import com.jeesite.modules.common.service.SysOfficeUnitService;
import com.jeesite.modules.msg.entity.content.PcMsgContent;
import com.jeesite.modules.msg.utils.MsgPushUtils;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.audit.entity.DcSupTaskAudit;
import com.jeesite.modules.task.audit.service.DcSupTaskAuditService;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfo;
import com.jeesite.modules.task.deploy.entity.DcSupTaskInfoRefine;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoAddService;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoRefineService;
import com.jeesite.modules.task.deploy.service.DcSupTaskInfoService;
import com.jeesite.modules.task.dict.entity.DcSupTaskInfoDict;
import com.jeesite.modules.task.dict.service.DcSupTaskInfoDictService;
import com.jeesite.modules.task.receive.entity.TaskReceiveDto;
import com.jeesite.modules.task.taskgroup.entity.DcSupTaskGroup;
import com.jeesite.modules.task.taskgroup.service.DcSupTaskGroupService;
import com.jeesite.modules.utils.Dict;
import com.jeesite.modules.utils.OfficeUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 任务部署-细化分解
 *
 * @author ya_jun
 */
@Controller
@RequestMapping(value = "${adminPath}/taskdeploy/dcSupTaskInfoRefine")
public class DcSupTaskInfoRefineController extends BaseController {

    /**
     * 获取数据
     */
    @ModelAttribute
    public DcSupTaskInfo get(String id, boolean isNewRecord) {
        return dcSupTaskInfoService.get(id, isNewRecord);
    }

    @Autowired
    private DcSupTaskInfoService dcSupTaskInfoService;
    @Autowired
    private DcSupTaskInfoDictService dcSupTaskInfoDictService;
    @Autowired
    private SysOfficeUnitService sysOfficeUnitService;
    @Autowired
    private UserService userService;
    @Autowired
    private DcSupTaskInfoRefineService dcSupTaskInfoRefineService;

    @Autowired
    private DcSupTaskGroupService dcSupTaskGroupService;
    @Autowired
    private SysMsgService sysMsgService;
    @Autowired
    @Lazy
    private DcSupTaskAuditService dcSupTaskAuditService;

    @Autowired
    private DcSupTaskInfoAddService dcSupTaskInfoAddService;
    /**
     * 查询列表-代提交
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:view")
    @RequestMapping(value = {"list"})
    public String listTodo(DcSupTaskInfo dcSupTaskInfo, Model model) {
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        // 任务年度
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        // 任务类型
        DcSupTaskInfoDict dcSupTaskInfoDict = new DcSupTaskInfoDict();
        dcSupTaskInfoDict.setDictStatus("0");
        List<DcSupTaskInfoDict> dicts = dcSupTaskInfoDictService.findList(dcSupTaskInfoDict);

        model.addAttribute("dicts", dicts);
        return "modules/task/deploy/refine/dcSupTaskInfoList";
    }

    /**
     * 查询列表-已提交
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:view")
    @RequestMapping(value = "listed")
    public String listDone(DcSupTaskInfo dcSupTaskInfo, Model model) {
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        // 任务年度
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        // 任务类型
        DcSupTaskInfoDict dcSupTaskInfoDict = new DcSupTaskInfoDict();
        dcSupTaskInfoDict.setDictStatus("0");
        List<DcSupTaskInfoDict> dicts = dcSupTaskInfoDictService.findList(dcSupTaskInfoDict);

        model.addAttribute("dicts", dicts);
        // 查询牵头领导
        User user = new User();
        user.setRoleCode("100016");
        user.setUserType("employee");
        List<User> list = userService.findList(user);
        model.addAttribute("userList", list);
        return "modules/task/deploy/refine/dcSupTaskInfoedList";
    }

    /**
     * 查询分页数据
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:view")
    @RequestMapping(value = "queryListData")
    @ResponseBody
    public Page<DcSupTaskInfo> queryListData(DcSupTaskInfo dcSupTaskInfo, HttpServletRequest request, HttpServletResponse response) {
        dcSupTaskInfo.setPage(new Page<>(request, response));
        dcSupTaskInfo.setNormalFlag("3");
        dcSupTaskInfo.setCreateUnit(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        if (dcSupTaskInfo.getDataLimit().equals("0") && EmpUtils.getEmployee().getEmpCode() !=null ){
            dcSupTaskInfo.setCreateBy(EmpUtils.getEmployee().getEmpCode());
        }
        Page<DcSupTaskInfo> page = dcSupTaskInfoService.findListPage(dcSupTaskInfo);

        // 如果不是草稿状态，生成分解进度信息
        if (!Dict.TaskStatus.STATUS_1.equals(dcSupTaskInfo.getTaskStatus())) {
            dcSupTaskInfoRefineService.generateRefineProgress(page.getList());
        }
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:view")
    @RequestMapping(value = "form")
    public String form(DcSupTaskInfo dcSupTaskInfo, Model model) {
        DcSupTaskGroup dcSupTaskGroup = new DcSupTaskGroup();
        dcSupTaskGroup.setCreateBy(UserUtils.getUser().getUserCode());
        List<DcSupTaskGroup> groupList = dcSupTaskGroupService.findList(dcSupTaskGroup);
        model.addAttribute("groupList", groupList);
        // 任务年度
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);

        // 细化分解任务，使用“督办字号（普通）”
        dcSupTaskInfo.setNormalFlag("3");

        // 为联系人和联系单位赋初值
        User currUser = UserUtils.getUser();
        dcSupTaskInfo.setContactName(StringUtils.isBlank(dcSupTaskInfo.getContactName()) ? currUser.getUserName() : dcSupTaskInfo.getContactName());
        dcSupTaskInfo.setContactPhone(StringUtils.isBlank(dcSupTaskInfo.getContactPhone()) ? currUser.getMobile() : dcSupTaskInfo.getContactPhone());

        // 初始化排序编号
        if (StringUtils.isBlank(dcSupTaskInfo.getSortNum())) {
            Integer maxSortNum = dcSupTaskInfoService.getMaxSortNum();
            if (maxSortNum == null) {
                maxSortNum = 1;
            } else {
                maxSortNum = maxSortNum + 10;
            }
            dcSupTaskInfo.setSortNum(dcSupTaskInfo.getSortNum() != null ? dcSupTaskInfo.getSortNum() : maxSortNum + "");
        }
        Integer messageNumber = dcSupTaskInfoService.getMaxMessageNumber();
        if (StringUtils.isBlank(dcSupTaskInfo.getMessageNumber())) {
            if (messageNumber == null) {
                messageNumber = 0;
            }
            dcSupTaskInfo.setMessageNumber(messageNumber + 1 + "");
        } else {
            if (dcSupTaskInfo.getMessageNumber().contains("〕")) {
                dcSupTaskInfo.setMessageNumber(dcSupTaskInfo.getMessageNumber().split("〕")[1]);
            }
        }

        // 查询牵头领导
        User user = new User();
        user.setRoleCode("100016");
        user.setUserType("employee");
        List<User> list = userService.findList(user);

        // 查询任务类型列表
        DcSupTaskInfoDict dcSupTaskInfoDict = new DcSupTaskInfoDict();
        dcSupTaskInfoDict.setDictStatus("0");
        List<DcSupTaskInfoDict> dicts = dcSupTaskInfoDictService.findList(dcSupTaskInfoDict);
        model.addAttribute("auditContent", "无");
        if(StringUtils.inString(dcSupTaskInfo.getTaskStatus(),"3","4","5","6")){
            DcSupTaskAudit audit = new DcSupTaskAudit();
            audit.setTaskId(dcSupTaskInfo.getId());
            List<DcSupTaskAudit> dcSupTaskAudits = dcSupTaskAuditService.findList(audit);
            DcSupTaskAudit dcSupTaskAudit = dcSupTaskAudits.get(0);
            model.addAttribute("auditContent", dcSupTaskAudit.getAuditOption()==null?"无":dcSupTaskAudit.getAuditOption());
        }

        model.addAttribute("msgType", "dc_num_common");
        model.addAttribute("userList", list);
        model.addAttribute("dicts", dicts);
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);

        // 2已发布、3任务部署审核通过、5秘书长审核通过、7已确认、8进行中、9已结束
        if (StringUtils.inString(dcSupTaskInfo.getTaskStatus(), "2", "3", "5", "7", "8", "9")) {
            return "modules/task/deploy/refine/dcSupTaskInfoDetailForm";
        }
        return "modules/task/deploy/refine/dcSupTaskInfoForm";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:edit")
    @PostMapping(value = "save")
    @RepeatSubmit
    @ResponseBody
    public String save(@Validated DcSupTaskInfo dcSupTaskInfo) {
        // 用户重新部署细化分解任务时，将此处的单条消息置为已读
        if("4".equals(dcSupTaskInfo.getTaskStatus())){
            // 只有状态为任务部署审核驳回的任务，执行此处
            sysMsgService.makeMsgReadByBiz(dcSupTaskInfo.getId(), "audit_reject_deploy", UserUtils.getUser().getUserCode());
        }

        dcSupTaskInfoService.uniqueMessageNumber(dcSupTaskInfo);
        dcSupTaskInfoRefineService.saveTask(dcSupTaskInfo);
        if (StringUtils.equals(dcSupTaskInfo.getTaskStatus(), "1")) {
            return renderResult(Global.TRUE, text("保存草稿成功！"));
        }
        return renderResult(Global.TRUE, text("发布任务成功！"));
    }

    /**
     * 分解确认列表
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:refine")
    @RequestMapping(value = "refineList")
    public String refineList(DcSupTaskInfo dcSupTaskInfo, Model model) {
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        // 任务年度
        Integer currentYear = Integer.parseInt(DateUtils.getYear());
        model.addAttribute("yearList", OfficeUtil.getYearList(currentYear));
        model.addAttribute("currentYear", currentYear);
        // 任务类型
        DcSupTaskInfoDict dcSupTaskInfoDict = new DcSupTaskInfoDict();
        dcSupTaskInfoDict.setDictStatus("0");
        List<DcSupTaskInfoDict> dicts = dcSupTaskInfoDictService.findList(dcSupTaskInfoDict);

        model.addAttribute("dicts", dicts);
        return "modules/task/deploy/refine/dcSupTaskInfoRefineList";
    }

    @RequestMapping(value = "refineUpdateList")
    public String refineUpdateList(DcSupTaskInfo dcSupTaskInfo, Model model) {
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        return "modules/task/deploy/refine/dcSupTaskInfoRefineUpdateList";
    }

    /**
     * 查询分解确认列表分页数据
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:refine")
    @RequestMapping(value = "queryRefineListData")
    @ResponseBody
    public Page<DcSupTaskInfoRefine> queryRefineListData(DcSupTaskInfo dcSupTaskInfo, HttpServletRequest request, HttpServletResponse response) {
        dcSupTaskInfo.setPage(new Page<>(request, response));
        dcSupTaskInfo.setTaskLeaderOrg(sysOfficeUnitService.getLatestUnitByOffice().getOfficeCode());
        Page<DcSupTaskInfoRefine> page = dcSupTaskInfoRefineService.findRefinePage(dcSupTaskInfo);
        return page;
    }

    @RequestMapping(value = "queryRefineUpdateListData")
    @ResponseBody
    public Page<DcSupTaskInfoRefine> queryRefineUpdateListData(DcSupTaskInfo dcSupTaskInfo, HttpServletRequest request, HttpServletResponse response) {
        dcSupTaskInfo.setPage(new Page<>(request, response));
        Page<DcSupTaskInfoRefine> page = dcSupTaskInfoRefineService.queryRefineUpdateListData(dcSupTaskInfo);
        return page;
    }

    @RequestMapping(value = "transfer")
    public String transfer(TaskReceiveDto taskReceive, Model model) {
        Office currentOffice = sysOfficeUnitService.getLatestUnitByOffice();
        String parentCode = currentOffice.getOfficeCode();
        String parentName = currentOffice.getOfficeName();
        model.addAttribute("parentCode", parentCode);
        model.addAttribute("parentName", parentName);
        taskReceive.setLeaderOrgCode(currentOffice.getOfficeCode());
        model.addAttribute("taskReceiveFour", taskReceive);
        return "modules/task/deploy/refine/transfer";
    }

    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:refine")
    @PostMapping(value = "doTransfer")
    @RepeatSubmit
    @ResponseBody
    public String doTransfer(DcSupTaskInfoRefine taskInfoRefine) {
        dcSupTaskInfoRefineService.doTransfer(taskInfoRefine);
        return renderResult(Global.TRUE, text("工作安排成功！"));
    }

    /**
     * 分解确认表单
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:refine")
    @RequestMapping(value = "refineForm")
    public String refineForm(DcSupTaskInfoRefine taskInfoRefine, Model model) {
        // 分解信息
        taskInfoRefine = dcSupTaskInfoRefineService.get(taskInfoRefine);
        model.addAttribute("taskInfoRefine", taskInfoRefine);
        // 任务信息
        DcSupTaskInfo dcSupTaskInfo = this.get(taskInfoRefine.getTaskId(), false);
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        return "modules/task/deploy/refine/dcSupTaskInfoRefineForm";
    }

    @RequestMapping(value = "refineUpdateForm")
    public String refineUpdateForm(DcSupTaskInfoRefine taskInfoRefine, Model model) {
        // 分解信息
        taskInfoRefine = dcSupTaskInfoRefineService.get(taskInfoRefine);
        model.addAttribute("taskInfoRefine", taskInfoRefine);
        // 任务信息
        DcSupTaskInfo dcSupTaskInfo = this.get(taskInfoRefine.getTaskId(), false);
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        return "modules/task/deploy/refine/refineUpdateForm";
    }

    @RequestMapping(value = "refineUpdateTime")
    public String refineUpdateTime(DcSupTaskInfoRefine taskInfoRefine, Model model) {
        // 分解信息
        taskInfoRefine = dcSupTaskInfoRefineService.get(taskInfoRefine);
        model.addAttribute("taskInfoRefine", taskInfoRefine);
        // 任务信息
        DcSupTaskInfo dcSupTaskInfo = this.get(taskInfoRefine.getTaskId(), false);
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        return "modules/task/deploy/refine/refineUpdateTime";
    }

    /**
     * 任务分解确认
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:refine")
    @PostMapping(value = "refine")
    @RepeatSubmit
    @ResponseBody
    public String refine(DcSupTaskInfoRefine taskInfoRefine) {
        // 用户分阶段报送时，将此处的多条消息置为已读
        sysMsgService.makeMsgReadByBiz(taskInfoRefine.getTaskId() + "_" + taskInfoRefine.getTaskLeaderOrg(), "confirm_refine", null);
        // 将审核驳回的单条消息置为已读
        sysMsgService.makeMsgReadByBiz(taskInfoRefine.getTaskId(), "audit_reject_refine", UserUtils.getUser().getUserCode());

        dcSupTaskInfoRefineService.refine(taskInfoRefine);
        return renderResult(Global.TRUE, text("分解确认成功！"));
    }

    @PostMapping(value = "updateRefine")
    @RepeatSubmit
    @ResponseBody
    public String updateRefine(DcSupTaskInfoRefine taskInfoRefine) {
        for (int i = 0; i < taskInfoRefine.getDcSupTaskInfoAddList().size(); i++) {
            dcSupTaskInfoAddService.saveRefine(taskInfoRefine.getDcSupTaskInfoAddList().get(i));
        }
        return renderResult(Global.TRUE, text("修改成功！"));
    }
    @PostMapping(value = "updateRefineTime")
    @RepeatSubmit
    @ResponseBody
    public String updateRefineTime(DcSupTaskInfoRefine taskInfoRefine) {
        for (int i = 0; i < taskInfoRefine.getDcSupTaskInfoAddList().size(); i++) {
            dcSupTaskInfoAddService.updateRefineTime(taskInfoRefine.getDcSupTaskInfoAddList().get(i));
        }
        return renderResult(Global.TRUE, text("修改成功！"));
    }

    /**
     * 查看任务详情
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:view")
    @RequestMapping(value = "detail")
    public String detail(DcSupTaskInfo dcSupTaskInfo, Model model) {
        model.addAttribute("dcSupTaskInfo", dcSupTaskInfo);
        return "modules/task/deploy/refine/dcSupTaskInfoDetail";
    }

    /**
     * 导入督办数据
     */
    @RequiresPermissions("taskdeploy:dcSupTaskInfoRefine:edit")
    @PostMapping(value = "importData")
    @ResponseBody
    public String importData(MultipartFile file) {
        try {
            String message = dcSupTaskInfoRefineService.importData(file);
            return renderResult(Global.TRUE, "posfull:"+message);
        } catch (Exception ex) {
            return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
        }
    }

    @RequestMapping(value = "refineDelete")
    public String refineDelete(String id){
        dcSupTaskInfoRefineService.refineDelete(id);
        return renderResult(Global.TRUE, "删除成功");
    }
}
